import React, { PureComponent } from 'react'
import 'cesium/Source/Widgets/widgets.css'

import { connect } from 'react-redux'

import ImageryThemeGL from './imageryThemeGL'
import { CenterMapWarpper } from './style'
import { fetchProjectList } from "@/store/modules/linping-screen";

export class Index extends PureComponent {
    constructor(props) {
        super()
        this.state = {
            projects: [
                // {
                //     id: "1001",
                //     lonlat: [120.3025724675529, 30.414819264166333],
                //     projectName: '未来科技城测试项目'
                // },
                // {
                //     id: "1002",
                //     lonlat: [120.3225724675529, 30.404819264166333],
                //     projectName: '临平体育场'
                // }
            ],
            showTooltip: false,
            streetNames: [],
        }

    }
    initMap() {
        const _this = this
        //天地图
        // let [tiandiVecModel, tiandiImgModel] = getProviderViewModels();
        const viewer = new Cesium.Viewer("cesiumContainer", {
            contextOptions: {
                requestWebgl1: true,
            },
            // imageryProviderViewModels: [tiandiVecModel, tiandiImgModel],
            baseLayerPicker: false,//隐藏默认底图选择控件
            geocoder: false, //地理编码器小部件
            homeButton: false, //首页按钮
            timeline: false, //时间轴小部件
            navigationHelpButton: false, //导航帮助按钮
            sceneModePicker: false, // SceneModePicker 小部件
            animation: false, // 隐藏左下角的仪表盘播放动画按钮
            infoBox: false, //创建 InfoBox 小部件
            fullscreenButton: false, //全屏按钮
            //设置背景透明
            orderIndependentTranslucency: false,
            scene3DOnly: true,
            shadows: true,
        })
        //重点，必须设置该配置
        viewer.scene.globe.depthTestAgainstTerrain = false;
        viewer.imageryLayers.get(0).show = false;
        viewer.scene.skyBox.show = false;
        viewer.scene.sun.show = false;
        viewer.scene.moon.show = false;
        viewer.scene.globe.baseColor = Cesium.Color.BLACK;
        viewer.scene.screenSpaceCameraController.tiltEventTypes = [];
        // viewer.scene.screenSpaceCameraController.enableRotate=false;


        //天地图
        // var imageryProvider = createTdtImageryProvider({
        //   layer: "vec",
        //   appKey: "7629c26d398f4c7bd23687e7ad6928ee",
        // });
        // var cvaProvider = createTdtImageryProvider({
        //   layer: "cva",
        //   appKey: "7629c26d398f4c7bd23687e7ad6928ee",
        // });
        //政务图
        //tdt_biaozhunyangshi_2017 标准样式
        //tdt_kejiganyangshi_2017  科技样式
        // const url1 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000009/mapserver/vmap/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017'	
        // const url2 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000011/mapserver/label/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017'
        // const url1 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220315000001/services/wmts/emap/default/oss'       //atg.biz.gettile  电子地图服务调用地址
        // const url2 = 'https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220323000008/services/wmts/emap_lab/default/oss'	  //atg.biz.gettile_lab 电子地图标注服务调用地址 
        // var imageryProvider = store.createGovImageryProvider({
        //   layer: "emap",
        //   url:"https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220315000001/services/wmts/emap/default/oss"
        // });
        // var cvaProvider = store.createGovImageryProvider({
        //   layer: "emap_lab",
        //   url:"https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220323000008/services/wmts/emap_lab/default/oss"
        // });
        var imageryProvider = store.createGovImageryProvider({
            layer: "emap",
            url: "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000009/mapserver/vmap/WMTS/1.0/zjvmap/tdt_biaozhunyangshi_2017"
        });
        // var cvaProvider = store.createGovImageryProvider({
        //   layer: "emap_lab",
        //   url:"https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000011/mapserver/label/WMTS/1.0/zjvmap/tdt_biaozhunyangshi_2017"
        // });
        // var imageryProvider = store.createGovImageryProvider({
        //   layer: "emap",
        //   url: "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000009/mapserver/vmap/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017"
        // });
        var cvaProvider = store.createGovImageryProvider({
            layer: "emap_lab",
            url: "https://ibcdsg.zj.gov.cn:8443/restapi/prod/IC33000020220811000011/mapserver/label/WMTS/1.0/zjvmap/tdt_kejiganyangshi_2017"
        });

        // //接下来我们就要对这个图层进行处理
        var layer = viewer.imageryLayers.addImageryProvider(imageryProvider);
        layer.alpha = 0.9;
        var layer2 = viewer.imageryLayers.addImageryProvider(cvaProvider);
        layer2.alpha = 0.5;
        //创建主题，设置相关参数
        const theme = new ImageryThemeGL({
            bgColor: Cesium.Color.fromCssColorString("#6666ff"),//.BLUE,
            alpha: 0.9,
            invert: false, /*灰度不反转 */
            preMultiplyAlpha: true
        })
        //重写 layer._createTextureWebGL 方法
        var _createTextureWebGL = layer._createTextureWebGL;
        layer._createTextureWebGL = function (context, imagery) {
            var texture = _createTextureWebGL.bind(this)(context, imagery);
            var textureProcessed = theme.processTexture(context, texture);
            return textureProcessed || texture;
        };

        let yh = [120.2405724675529, 30.444819264166333];
        var scene = viewer.scene;
        // 将三维球定位到中国
        viewer.camera.flyTo({// fromDegrees()方法，将经纬度和高程转换为世界坐标
            destination: Cesium.Cartesian3.fromDegrees(yh[0], yh[1], 59000.0),
            orientation: {
                heading: 6.283185307179586,
                // 视角
                pitch: -1.5686521559334161,
                roll: 0,
            }
        })

        //加载gltf模型
        // var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        // Cesium.Cartesian3.fromDegrees(120.3025724675529, 30.414819264166333, 0.0));
        // var model = scene.primitives.add(Cesium.Model.fromGltf({
        //   url: "../Apps/SampleData/models/CesiumGround/Cesium_Ground.gltf",
        //   modelMatrix: modelMatrix,
        //   minimumPixelSize: 512,
        //   maximumScale: 200000
        // }));


        // const jsonData = `https://geo.datav.aliyun.com/areas_v3/bound/440000_full.json`;
        const jsonData = `https://lpws.lanchensl.cn/lpdp/linping.geojson`;
        // jsonData一定要json文件

        const promise = Cesium.GeoJsonDataSource.load(jsonData, {
            stroke: Cesium.Color.fromCssColorString("#bce672"),
            fill: Cesium.Color.fromCssColorString("#425066").withAlpha(0.8),
            strokeWidth: 3,
            markerSize: 10,
            markerSymbol: "?",
        }
        );
        promise.then(function (dataSource) {
            const streetNames = dataSource.entities.values.map(item => item.name).filter(v => v)
            _this.setState({ streetNames: [...streetNames] })
            // viewer.dataSources.add(dataSource);

            var entities = dataSource.entities.values;
            var colorHash = {};
            for (var o = 0; o < entities.length; o++) {
                var r = entities[o];
                //获取坐标
                let positions = r.polygon.hierarchy.getValue(Cesium.JulianDate.now()).positions;
                let polyCenter = Cesium.BoundingSphere.fromPoints(positions).center;
                polyCenter = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(polyCenter);
                let grpc = Cesium.Cartographic.fromCartesian(polyCenter, viewer.scene.globe.ellipsoid, new Cesium.Cartographic());
                let lng = Cesium.Math.toDegrees(grpc.longitude);
                let lat = Cesium.Math.toDegrees(grpc.latitude);

                //创建边缘线
                const polylines = scene.primitives.add(
                    new Cesium.PolylineCollection()
                );
                const polyline = polylines.add({
                    positions: positions,
                    width: 5.0,
                    show: true,
                    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 140000)
                });
                //添加街道
                const polygon = viewer.entities.add({
                    name: r.name,
                    polygon:
                    {
                        hierarchy: {
                            positions: positions
                        },
                        extrudedHeight: 0,
                        material: new Cesium.ColorMaterialProperty(Cesium.Color.fromCssColorString("#33ACFF").withAlpha(0.1)),
                        // arcType: Cesium.ArcType.RHUMB,
                        // height: 200,
                        // outline: true,
                        // outlineColor: Cesium.Color.fromCssColorString("#93b3e2"),
                        // outlineWidth: 0,

                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 140000),
                    }
                });
                // polylines.customShader=customShader;
                const material =
                    new Cesium.Material({
                        fabric: {
                            type: 'PolylinePulseLink',
                            uniforms: {
                                color: new Cesium.Color.fromCssColorString('#306090'),
                                image: '/cabe.png',
                                speed: 1,
                            },
                            source: 'czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                                    {\n\
                                        czm_material material = czm_getDefaultMaterial(materialInput);\n\
                                        vec2 st = materialInput.st;\n\
                                        vec4 colorImage = texture2D(image, vec2(fract((st.t - speed*czm_frameNumber*0.005)), st.t));\n\
                                        vec4 fragColor;\n\
                                        fragColor.rgb = color.rgb / 1.0;\n\
                                        fragColor = czm_gammaCorrect(fragColor);\n\
                                        material.alpha = colorImage.a * color.a;\n\
                                        material.diffuse = (colorImage.rgb+color.rgb)/2.0;\n\
                                        material.emission = fragColor.rgb;\n\
                                        return material;\n\
                                    }',
                        },
                        translucent: function () {
                            return true
                        },
                    });
                // polyline.material = material2;
                polyline.material = Cesium.Material.fromType(Cesium.Material.PolylineGlowType, {
                    color: Cesium.Color.fromCssColorString("#33ACFF").withAlpha(1),
                    glowPower: 0.1,
                    // taperPower:0.1,
                });

                // polyline.material= Cesium.Material.fromType(Cesium.Material.PolylineOutlineType, {
                //   color: Cesium.Color.BLUE.withAlpha(0.7),
                //   outlineColor:Cesium.Color.GREEN.withAlpha(0.7),
                //   outlineWidth:5
                // });

                // }
                // const polyline2 = polylines.add({
                //   positions: positions,
                //   width: 6.0,
                //   show: true,
                //   arcType: Cesium.ArcType.RHUMB
                // });
                // polyline2.material=  Cesium.Material.fromType(Cesium.Material.PolylineArrowType, {
                //   color: Cesium.Color.fromCssColorString("#00BFFF").withAlpha(1)
                // });
                r.nameID = o;   //给每条线添加一个编号，方便之后对线修改样式


                //           var customShader = new Cesium.CustomShader({
                //     lightingModel: Cesium.LightingModel.UNLIT,
                //     fragmentShaderText: `
                //         void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
                //             float _baseHeight = 0.0; // 物体的基础高度，需要修改成一个合适的建筑基础高度
                //             float _heightRange = 60.0; // 高亮的范围(_baseHeight ~ _baseHeight + _      heightRange) 默认是 0-60米
                //             float _glowRange = 300.0; // 光环的移动范围(高度)
                //             float vtxf_height = fsInput.attributes.positionMC.z-_baseHeight;
                //             float vtxf_a11 = fract(czm_frameNumber / 120.0) * 3.14159265 * 2.0;
                //             float vtxf_a12 = vtxf_height / _heightRange + sin(vtxf_a11) * 0.1;
                //             material.diffuse*= vec3(vtxf_a12, vtxf_a12, vtxf_a12);
                //             float vtxf_a13 = fract(czm_frameNumber / 360.0);
                //             float vtxf_h = clamp(vtxf_height / _glowRange, 0.0, 1.0);
                //             vtxf_a13 = abs(vtxf_a13 - 0.5) * 2.0;
                //             float vtxf_diff = step(0.005, abs(vtxf_h - vtxf_a13));
                //             material.diffuse += material.diffuse * (1.0 - vtxf_diff);
                //         }       
                //         `,
                // });


                // polygon.polygon.material= new Cesium.ImageMaterialProperty({
                //     transparent: true,//设置透明
                //     color: new Cesium.Color.fromCssColorString("#ffffff").withAlpha(0.1),
                //     image: "/tl.png",
                //     repeat: new Cesium.Cartesian2(1,2),
                //   });


                function DynamicWallMaterialProperty(options) {
                    this._definitionChanged = new Cesium.Event();
                    this._color = undefined;
                    this._colorSubscription = undefined;
                    this.color = options.color || Color.BLUE;
                    this.duration = options.duration || 1000;
                    this.trailImage = options.trailImage;
                    this._time = (new Date()).getTime();
                }

                /**
            * 带方向的墙体
            * @param {*} options.get:true/false
            * @param {*} options.count:数量 
            * @param {*} options.freely:vertical/standard
            * @param {*} options.direction:+/-
            */
                function _getDirectionWallShader(options) {
                    if (options && options.get) {
                        var materail = "czm_material czm_getMaterial(czm_materialInput materialInput)\n\
                                        {\n\
                                            czm_material material = czm_getDefaultMaterial(materialInput);\n\
                                            vec2 st = materialInput.st;";
                        if (options.freely == "vertical") { //（由下到上）
                            materail += "vec4 colorImage = texture2D(image, vec2(fract(st.s), fract(float(" + options.count + ")*st.t" + options.direction + " time)));\n\ ";
                        } else { //（逆时针）
                            materail += "vec4 colorImage = texture2D(image, vec2(fract(float(" + options.count + ")*st.s " + options.direction + " time), fract(st.t)));\n\ ";
                        }
                        //泛光
                        materail += "vec4 fragColor;\n\
                                            fragColor.rgb = (colorImage.rgb+color.rgb) / 1.0;\n\
                                            fragColor = czm_gammaCorrect(fragColor);\n\
                                            material.diffuse = colorImage.rgb;\n\
                                            material.alpha = colorImage.a;\n\
                                            material.emission = fragColor.rgb;\n\
                                            return material;\n\
                                        }";
                        return materail
                    }
                } Object.defineProperties(DynamicWallMaterialProperty.prototype, {
                    isConstant: {
                        get: function () {
                            return false;
                        }
                    },
                    definitionChanged: {
                        get: function () {
                            return this._definitionChanged;
                        }
                    },
                    color: Cesium.createPropertyDescriptor('color')
                });

                var MaterialType = 'wallType' + parseInt(Math.random() * 1000);
                DynamicWallMaterialProperty.prototype.getType = function (time) {
                    return MaterialType;
                };

                DynamicWallMaterialProperty.prototype.getValue = function (time, result) {
                    if (!Cesium.defined(result)) {
                        result = {};
                    }
                    result.color = Cesium.Property.getValueOrClonedDefault(this._color, time, Cesium.Color.WHITE, result.color);
                    result.image = this.trailImage;
                    if (this.duration) {
                        result.time = (((new Date()).getTime() - this._time) % this.duration) / this.duration;
                    }
                    viewer.scene.requestRender();
                    return result;
                };

                DynamicWallMaterialProperty.prototype.equals = function (other) {
                    return this === other ||
                        (other instanceof DynamicWallMaterialProperty
                            && Cesium.Property.equals(this._color, other._color))
                };

                Cesium.Material._materialCache.addMaterial(MaterialType, {
                    fabric: {
                        type: MaterialType,
                        uniforms: {
                            color: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
                            image: Cesium.Material.DefaultImageId,
                            time: -20
                        },
                        source: _getDirectionWallShader({
                            get: true,
                            count: 3.0,
                            freely: 'vertical',
                            direction: '-'
                        })
                    },
                    translucent: function (material) {
                        return true;
                    }
                });

                // viewer.entities.add({
                //   wall: {
                //     positions: positions,
                //     maximumHeights: new Array(positions.length).fill(500),
                //     minimunHeights: new Array(positions.length).fill(500),
                //     //  material: new Cesium.ImageMaterialProperty({
                //     //   transparent: true,//设置透明
                //     //   image: "/bb.png",
                //     //   repeat: new Cesium.Cartesian2(10, -10),
                //     // }),
                //     material: new DynamicWallMaterialProperty({ trailImage: '/tl.png', color: Cesium.Color.BLUE.withAlpha(0.7), duration: 1500 })
                //   },
                // });

                /** 添加街道名称背景框 */
                viewer.entities.add({
                    id: "p_" + o,
                    name: r.name,
                    position: Cesium.Cartesian3.fromDegrees(lng, lat),
                    show: true,
                    billboard: {
                        verticalOrigin: Cesium.VerticalOrigin.CENTER, //对齐方式
                        pixelOffset: new Cesium.Cartesian2(10, 2), //图片的上下左右偏移,正为右，下
                        sizeInMeters: false, //随着缩放而缩放
                        width: 173,
                        height: 60,
                        scale: 0.7,
                        image: "/qt2.png", //广告牌内容
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(30000, 60000),
                    },
                });
                /** 添加街道名称 */
                viewer.entities.add({
                    id: "l_" + o,
                    name: r.name,
                    position: Cesium.Cartesian3.fromDegrees(lng, lat),
                    // 文字
                    label: {
                        eyeOffset: new Cesium.Cartesian3(0, 0, -1000),
                        // 文本。支持显式换行符“ \ n”
                        text: r.name + " 100个",
                        // 字体样式，以CSS语法指定字体
                        font: '10pt 微软雅黑',
                        // 字体颜色
                        fillColor: Cesium.Color.WHITE,
                        // 是否显示背景颜色
                        showBackground: false,
                        // 字体边框
                        outline: false,
                        // 字体边框尺寸
                        outlineWidth: 1,
                        // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
                        scale: 1,
                        // 设置样式：FILL：填写标签的文本，但不要勾勒轮廓；OUTLINE：概述标签的文本，但不要填写；FILL_AND_OUTLINE：填写并概述标签文本。
                        style: Cesium.LabelStyle.FILL,
                        // 相对于坐标的水平位置
                        verticalOrigin: Cesium.VerticalOrigin.CENTER,
                        // 相对于坐标的水平位置
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
                        pixelOffset: new Cesium.Cartesian2(10, 0),
                        // 显示在距相机的距离处的属性，多少区间内是可以显示的
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(30000, 60000),
                        // 是否显示
                        show: true
                    }
                });
            }

            // //添加余杭
            // viewer.entities.add({
            //   id: "vl_yh",
            //   position: Cesium.Cartesian3.fromDegrees(yh[0], yh[1]),
            //   // 文字
            //   label: {
            //     eyeOffset: new Cesium.Cartesian3(0, 0, -1000),
            //     // 文本。支持显式换行符“ \ n”
            //     text: "临平区 599个",
            //     // 字体样式，以CSS语法指定字体
            //     font: '10pt 微软雅黑',
            //     // 字体颜色
            //     fillColor: Cesium.Color.WHITE,
            //     // 背景颜色
            //     backgroundColor: Cesium.Color.fromCssColorString("#8911e1").withAlpha(0.9),
            //     // 是否显示背景颜色
            //     showBackground: true,
            //     // 字体边框
            //     outline: true,
            //     // 字体边框颜色
            //     outlineColor: Cesium.Color.WHITE,
            //     // 字体边框尺寸
            //     outlineWidth: 10,
            //     // 应用于图像的统一比例。比例大于会1.0放大标签，而比例小于会1.0缩小标签。
            //     scale: 1.0,
            //     // 设置样式：FILL：填写标签的文本，但不要勾勒轮廓；OUTLINE：概述标签的文本，但不要填写；FILL_AND_OUTLINE：填写并概述标签文本。
            //     style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            //     // 相对于坐标的水平位置
            //     verticalOrigin: Cesium.VerticalOrigin.CENTER,
            //     // 相对于坐标的水平位置
            //     horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
            //     // 该属性指定标签在屏幕空间中距此标签原点的像素偏移量
            //     pixelOffset: new Cesium.Cartesian2(10, 0),
            //     // 显示在距相机的距离处的属性，多少区间内是可以显示的
            //     distanceDisplayCondition: new Cesium.DistanceDisplayCondition(30000, 200000),
            //     // 是否显示
            //     show: true
            //   }
            // });
            var temp = new Array();
            window.Hightlightline = function (nameid) {
                // var exists = temp.indexOf(nameid);
                // if (exists <= -1) {
                //   Highlight(nameid, 50, 50);
                //   temp.push(nameid);  // 添加线nameID到数组，
                // }
                // else  //已经是高亮状态了 再次点击修改为原始状态
                // {
                //   Highlight(nameid, 10, 10);
                //   temp.splice(exists, 1);  //删除对应的nameID
                // }
            }
            var om = null;
            window.Highlight = function (nameid, width1, width2) {
                // for (var o = 0; o < entities.length; o++) {
                //   var m = entities[o];
                //   if (om == null) om = m.polygon.material;
                //   if (nameid == o) {
                //     console.log("变换样式!");
                //     console.log(m);
                //     m.polygon.material = new Cesium.PolylineGlowMaterialProperty({
                //       glowPower: .1, //一个数字属性，指定发光强度，占总线宽的百分比。
                //       color: Cesium.Color.ORANGERED.withAlpha(.9)
                //     })
                //   } else {
                //     m.polygon.material = om;
                //   }
                // }
            }



        });
        // viewer.flyTo(promise);
        //-------------------------------------------------------------------------

        viewer.scene.light = new Cesium.DirectionalLight({
            direction: Cesium.Cartesian3.fromDegrees(yh[0], yh[1])
        })
        const testDataSource = new Cesium.CustomDataSource("dian")
        const entities = viewer.entities;
        /** 添加项目点位 */
        this.state.projects.map((o) => {
            const lng = Number(o.projectLng)
            const lat = Number(o.projectLat)
            if (o.projectLng && o.projectLat && Number(o.projectLng) && Number(o.projectLat)) {
                const data = ({
                    projectId: "p_" + o.id,
                    projectName: o.projectName,
                    builderLicenceNum: o.builderLicenceNum,
                    position: Cesium.Cartesian3.fromDegrees(lng, lat),
                    show: true,
                    billboard: {
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM, //对齐方式
                        pixelOffset: new Cesium.Cartesian2(10), //图片的上下左右偏移,正为右，下
                        sizeInMeters: false, //随着缩放而缩放
                        width: 24,
                        height: 48,
                        image: "/pos.png", //广告牌内容
                        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 30000),
                    },
                });
                testDataSource.entities.add(data);
            }
        });
        viewer.dataSources.add(testDataSource);
        combineListener();
        /**点聚合功能实现 */
        function combineListener() {
            testDataSource.clustering.enabled = true;
            testDataSource.clustering.pixelRange = 40;
            testDataSource.clustering.minimumClusterSize = 2;

            testDataSource.clustering.clusterEvent.addEventListener(function (clusteredEntities, cluster) {
                // 关闭自带的显示聚合数量的标签
                cluster.label.show = false;
                cluster.billboard.show = true;
                cluster.billboard.id = cluster.label.id;
                cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
                cluster.billboard.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, 160000),
                    // 根据聚合数量的多少设置不同层级的图片以及大小
                    // if (clusteredEntities.length >= 10) {
                    cluster.billboard.image = combineIconAndLabel(
                        "/right2-num-bg.png",
                        clusteredEntities.length,
                        40
                    );
                cluster.billboard.width = 64;
                cluster.billboard.height = 64;
                // }
                // else if (clusteredEntities.length >= 6) {
                //     cluster.billboard.image = combineIconAndLabel(
                //         "/right2-num-bg.png",
                //         clusteredEntities.length,
                //         10
                //     );
                //     cluster.billboard.width = 10;
                //     cluster.billboard.height = 10;
                // } else if (clusteredEntities.length >= 3) {
                //     cluster.billboard.image = combineIconAndLabel(
                //         "/right2-num-bg.png",
                //         clusteredEntities.length,
                //         10
                //     );
                //     cluster.billboard.width = 10;
                //     cluster.billboard.height = 10;
                // } else {
                //     cluster.billboard.image = combineIconAndLabel(
                //         "/right2-num-bg.png",
                //         clusteredEntities.length,
                //         10
                //     );
                //     cluster.billboard.width = 10;
                //     cluster.billboard.height = 10;
                // }
            });
            // 创建画布对象
            function combineIconAndLabel(url, label, size) {
                let canvas = document.createElement("canvas");
                canvas.width = size * 3.5;
                canvas.height = size * 3.5;
                let ctx = canvas.getContext("2d");
                let promise = new Cesium.Resource.fetchImage(url).then((image) => {
                    // 异常判断
                    try {
                        ctx.drawImage(image, -5, -5);
                    } catch (e) {
                        console.log(e);
                    }
                    // 渲染字体
                    // font属性设置顺序：font-style, font-variant, font-weight, font-size, line-height, font-family
                    ctx.fillStyle = Cesium.Color.WHITE.toCssColorString();
                    ctx.font = "bold 32px Microsoft YaHei";
                    ctx.textAlign = "center";
                    ctx.textBaseline = "middle";
                    ctx.fillText(label, 30, 32);

                    return canvas;
                });
                return promise;
            }
        }
        //  let endPosition = new Cesium.Cartesian3.fromDegrees(120.3225724675529, 30.404819264166333);
        //  let factor = 0;
        // 添加模型
        //  entities.add({
        //     id: "test3",
        //      position: Cesium.Cartesian3.fromDegrees(120.3236724675529, 30.404819264166333),
        //     // position: new Cesium.CallbackProperty(function() {
        //     //    if (factor < 100) {
        //     //       factor++;
        //     //    }
        //     //    // 动态更新位置
        //     //    return Cesium.Cartesian3.lerp(startPosition, endPosition, factor / 100.0, new Cesium.Cartesian3());
        //     // }, true),
        //     billboard: {
        //       verticalOrigin: Cesium.VerticalOrigin.BOTTOM, //对齐方式
        //       pixelOffset: new Cesium.Cartesian2(10), //图片的上下左右偏移,正为右，下
        //       sizeInMeters: false, //随着缩放而缩放
        //       width: 20,
        //       height: 40,
        //       image: "/pos.png", //广告牌内容
        //     },
        //  });

        if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {//判断是否支持图像渲染像素化处理
            viewer.resolutionScale = window.devicePixelRatio;
        }
        //是否开启抗锯齿
        viewer.scene.fxaa = true;
        viewer.scene.postProcessStages.fxaa.enabled = true;
        // console.log(viewer);

        function setHiddenTooltip() {
            const { mapClickHandle } = _this.props
            if (_this.state.showTooltip) {
                mapClickHandle(0, 0, false, {})
                _this.setState({
                    showTooltip: false
                })
            }

        }
        viewer.camera.changed.addEventListener(() => {
            let height = viewer.camera.positionCartographic.height;
            console.log("当前高度:", height);
            // for (var i = 0; i < entities.values.length; i++) {
            //   if (entities.values[i].id.indexOf("p_") != -1 && height > 30000) {
            //     entities.values[i].show = false;
            //   }
            //   if (entities.values[i].id.indexOf("p_") != -1 && height <= 30000) {
            //     entities.values[i].show = true;
            //   }
            //   if (entities.values[i].id.indexOf("l_") != -1 && height > 30000) {
            //     entities.values[i].show = true;
            //   }
            //   if (entities.values[i].id.indexOf("l_") != -1 && height <= 30000) {
            //     entities.values[i].show = false;
            //   }
            // }
        });
        // 鼠标点击
        viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
            var pickedFeature = viewer.scene.pick(movement.position);
            console.log(pickedFeature)


            console.log("pickedFeature:", pickedFeature)
            //鼠标是否点到线上
            if (typeof (pickedFeature) === "undefined" || pickedFeature.id === undefined) {
                setHiddenTooltip()
                return
            }
            // 判断点击的是否 是聚合点
            if (Array.isArray(pickedFeature.id)) {
                // let cartesian = viewer.scene.globe.pick(viewer.camera.getPickRay(movement.position), viewer.scene);
                // // 世界坐标转换为弧度
                // let ellipsoid = viewer.scene.globe.ellipsoid;
                // let cartographic = ellipsoid.cartesianToCartographic(cartesian);
                // // 弧度转换为经纬度
                // let lon = Cesium.Math.toDegrees(cartographic.longitude);  // 经度
                // let lat = Cesium.Math.toDegrees(cartographic.latitude);   // 纬度

                // console.log("点击的的经纬度坐标是：", cartesian);
                // viewer.camera.flyTo({// fromDegrees()方法，将经纬度和高程转换为世界坐标
                //     destination: Cesium.Cartesian3.fromDegrees(lon, lat, 10000.0),
                //     orientation: {
                //         heading: 6.283185307179586,
                //         // 视角
                //         pitch: -1.5686521559334161,
                //         roll: 0,
                //     }
                // })
                return
            }
            const { name, projectName, projectId, builderLicenceNum } = pickedFeature.id
            const { x, y } = movement.position
            const { streetNames } = _this.state
            const { mapClickHandle } = _this.props
            let params = {}
            if (streetNames.includes(name)) {
                params = { name: name }

            } else if (projectName && projectId) {
                params = { name: projectName, projectId, builderLicenceNum }
            }
            mapClickHandle(x, y, true, params)
            _this.setState({
                showTooltip: true
            })
            // _this.setState({ streetName: name, modalOpen: true });
            // var name_id = pickedFeature.id.nameID;  //获取每条线的nameID
            // Hightlightline(name_id);


        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
            Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
        );

        // 鼠标左键按下并且移动鼠标
        viewer.screenSpaceEventHandler.setInputAction(function () {
            viewer.screenSpaceEventHandler.setInputAction(function () {
                if (_this.state.showTooltip) {
                    setHiddenTooltip()
                }
            }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
        }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

        // 鼠标左键抬起--->移除鼠标移动事件
        viewer.screenSpaceEventHandler.setInputAction(function () {
            viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
                Cesium.ScreenSpaceEventType.MOUSE_MOVE
            );
        }, Cesium.ScreenSpaceEventType.LEFT_UP);



        // 鼠标滚轮滚动
        viewer.screenSpaceEventHandler.setInputAction(function () {

            if (_this.state.showTooltip) {
                setHiddenTooltip()
            }

        }, Cesium.ScreenSpaceEventType.WHEEL);

        // 鼠标移动
        viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
            let pickedFeatureStart = viewer.scene.pick(movement.startPosition);
            let pickedFeatureEnd = viewer.scene.pick(movement.endPosition);
            // console.log('鼠标滑动结束位置实体对象',pickedFeatureEnd)
            // console.log('鼠标滑动开始位置实体对象',pickedFeatureStart)
        }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    }
    async componentDidMount() {
        await this.props.getProjectList()
        const { projectList } = this.props
        this.setState({
            projects: [...projectList]
        })
        this.initMap()
    }
    render() {
        return (
            <CenterMapWarpper>
                <div id="cesiumContainer" className='center-map-container' />
            </CenterMapWarpper>

        )
    }
}


const mapStateToProps = (state) => {
    return {
        projectList: state.linpingScreen.projectList
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        getProjectList: () => dispatch(fetchProjectList())
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Index)